<template>
  <div class="app-container">
    <!-- 用户列表 -->
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="searchObj.username" placeholder="登录名称"/>
      </el-form-item>

      <el-form-item>
        <el-input v-model="searchObj.mobile" placeholder="手机号码"/>
      </el-form-item>  

      <el-form-item>
        <el-select v-model="searchObj.state" clearable placeholder="用户状态">
          <el-option :value="1" label="启用"/>
          <el-option :value="0" label="停用"/>
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchObj.begin"
          type="datetime"
          placeholder="选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="searchObj.end"
          type="datetime"
          placeholder="选择截止时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetchData()">查询</el-button>
        <el-button type="default" @click="resetData()">清空</el-button>
      </el-form-item>  
    </el-form>

    <!-- 工具条 -->
    <div>
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="addUser()" v-if="hasPerm('system:user:add')">添加</el-button>
      <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeRows()" v-if="hasPerm('system:user:remove')">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="数据加载中"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange">

      <el-table-column
        type="selection"
        width="55" />

      <el-table-column
        label="序号"
        width="70"
        align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="username" label="登录名称" align="center" width="160" />

      <el-table-column prop="realName" label="用户名称" align="center" width="160" />

      <el-table-column prop="mobile" label="手机" align="center" width="160" />

      <!-- <el-table-column label="用户状态" align="center" width="160">
        <template slot-scope="scope">
          {{ scope.row.state===1?'启用':'停用' }}
        </template>
      </el-table-column> -->
      <el-table-column label="用户状态" align="center" width="200">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.state"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column prop="gmtCreate" label="创建时间" align="center" width="160"/>

      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="updateUser(scope.row.id)" v-if="hasPerm('system:user:update')">编辑</el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeDataById(scope.row.id)" v-if="hasPerm('system:user:remove')">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

       <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      style="padding: 30px 0; text-align: center;"
      layout="total, prev, pager, next, jumper"
      @current-change="fetchData"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="form.username" :disabled="disabled" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="用户密码" v-if="form.id == undefined" prop="password">
          <el-input type="password" v-model="form.password" placeholder="请输入用户密码" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>  
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio :label='1'>启用</el-radio>
            <el-radio :label='0'>停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="saveBtn" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import userApi from '@/api/system/user'
import roleApi from '@/api/system/role'

export default {

  data() {
    return {
      listLoading: true, // 是否显示loading信息
      list: null, // 数据列表
      total: 0, // 总记录数
      page: 1, // 页码
      limit: 10, // 每页记录数
      searchObj: {},// 查询条件
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      form: {},
      multipleSelection: [], // 批量选择中选择的记录列表
      // 表单校验
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        sex: [
          { required: true, message: "请选择性别", trigger: "blur" }
        ],
        roleIds: [
          { required: true, message: "请选择角色", trigger: "blur" }
        ]
      },
      saveBtn: false,
      options: [{
          value: 0,
          label: '男'
        }, {
          value: 1,
          label: '女'
        }, {
          value: 2,
          label: '未知'
        }
      ],
      roleOptions: [],
      disabled: false
    }
  },
    
  created() { // 当页面加载时获取数据
    this.fetchData();
  },
    
  methods: {
    // 表单重置
    reset() {
      this.form = {};
    },
    // 列表
    fetchData(page = 1) { // 调用api层获取数据库中的数据
      this.page = page
      this.listLoading = true
      userApi.userList(this.page, this.limit, this.searchObj).then(response => {
        // debugger 设置断点调试
        if (response.code === 200) {
          this.list = response.data.records
          this.total = response.data.total
        }
        this.listLoading = false
      })
    },
    resetData() {
        this.searchObj = {}
        this.fetchData()
    },
    // 当表格复选框选项发生变化的时候触发
    handleSelectionChange(selection) {
      console.log(selection)
      this.multipleSelection = selection
    },

    // 添加
    addUser(){
      this.reset();
      this.open = true
      this.title = "添加用户";
      roleApi.allRoleList().then(response =>{
        this.roleOptions = response.data
        //console.log(response)
      })
    },
    // 修改
    updateUser(id){
      this.reset();
      this.disabled = true
      roleApi.allRoleList().then(response =>{
        this.roleOptions = response.data
        //console.log(response)
      })
      userApi.getById(id).then(response => {
        this.form = response.data;
        this.form.roleIds = response.data.roleIds;
        this.open = true;
        this.title = "修改用户";
      });
    },

    saveData(form){
      userApi.addUser(form).then(response =>{
        if(response.code ===200) {
          this.$message({
            type: 'success',
            message: '添加成功'
          })
          this.open = false;
          this.saveBtn = false
          this.fetchData();
        }
      });
    },
    updateData(form){
      userApi.updateUser(form).then(response =>{
        if(response.code ===200) {
          this.$message({
          type: 'success',
          message: '修改成功'
        })
        this.open = false;
        this.saveBtn = false
        this.fetchData();
        }
      });
    },
    // 修改用户状态
    handleStatusChange(row){
      console.log(row.state)
      let text = row.state === 1 ? "启用" : "停用";
      this.$confirm('确认要' + text + '“' + row.username + '”用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        // 遍历selection，将id取出放入id列表
        return userApi.changeUserState(row.id, row.state)
      }).then(() => {
          this.fetchData(this.page)
          this.$message({
            type: 'success',
            message: text + "成功"
          })
        }).catch(function() {
          row.state = row.state === "0" ? "1" : "0";
      });
    },
    // 删除
    removeDataById(id){
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        return userApi.removeById(id)
      }).then((response) => {
        this.fetchData(this.page)
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    submitForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.saveBtn = true
          let form = this.form
          // 修改
          if (form.id != undefined) {
            console.log(form)
            this.updateData(form)
          } else {// 新增
            this.saveData(form)
          }
          console.log(this.form)
        }
      })
    },
    cancel(){
      this.open = false;
      this.reset();
    },
    removeRows(){
      if (this.multipleSelection.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的记录!'
        })
        return
      }

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        // 遍历selection，将id取出放入id列表
        var idList = []
        this.multipleSelection.forEach(item => {
          idList.push(item.id)
        // console.log(idList)
        })
        // 调用api
        return userApi.removeBatchs(idList)
      }).then((response) => {
        this.fetchData(this.page)
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
  }
}
</script>